import pymysql
import configparser
import os
import time

# --- 获取配置文件路径 ---
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_FILE = os.path.join(BASE_DIR, 'config.ini')

def _get_db_config():
    """读取并返回数据库配置字典"""
    try:
        config = configparser.ConfigParser()
        if not os.path.exists(CONFIG_FILE):
            print(f"错误: 配置文件 {CONFIG_FILE} 不存在！")
            return None
        config.read(CONFIG_FILE, encoding='utf-8')

        db_config = {
            'host': config.get('Database', 'host'),
            'port': config.getint('Database', 'port'),
            'user': config.get('Database', 'user'),
            'password': config.get('Database', 'password'),
            'database': config.get('Database', 'database'),
            'charset': 'utf8mb4',
            'connect_timeout': 10,
            'cursorclass': pymysql.cursors.DictCursor # 使用字典游标
        }
        # print(f"读取配置: {db_config['host']}:{db_config['port']}") # Debug
        return db_config
    except configparser.Error as e:
        print(f"读取配置文件错误: {e}")
        return None
    except Exception as e:
        print(f"获取数据库配置时发生未知错误: {e}")
        return None

def execute_query(query, params=None, fetch_one=False, fetch_all=False):
    """执行查询语句 (SELECT) - 使用 PyMySQL"""
    db_config = _get_db_config()
    if not db_config:
        return None

    conn = None
    cursor = None
    try:
        # print("查询: 建立新连接...") # Debug
        conn = pymysql.connect(**db_config)
        # print("查询: 连接成功。创建游标...") # Debug
        cursor = conn.cursor() # cursorclass 已在 config 中指定为 DictCursor
        # print(f"查询: 执行 {query[:60]}... 参数: {params}") # Debug
        cursor.execute(query, params)
        # print("查询: 执行完毕。获取结果...") # Debug
        if fetch_one:
            result = cursor.fetchone()
            # print(f"查询: fetchone 结果: {result}") # Debug
            return result
        elif fetch_all:
            result = cursor.fetchall()
            # print(f"查询: fetchall 结果数量: {len(result) if result else 0}") # Debug
            return result
        else:
            # print("查询: 无需获取结果。") # Debug
            return None # 或者可以根据需要返回 cursor.rowcount
    except pymysql.Error as err:
        print(f"数据库查询失败 (PyMySQL): {err} (查询: {query[:60]}...) ({params})")
        return None
    except Exception as e:
        print(f"执行数据库查询时发生未知错误 (PyMySQL): {e}")
        return None
    finally:
        if cursor:
            # print("查询: 关闭游标...") # Debug
            cursor.close()
        if conn:
            # print("查询: 关闭连接...") # Debug
            conn.close()

def execute_update(query, params=None):
    """执行更新/插入/删除语句 - 使用 PyMySQL"""
    db_config = _get_db_config()
    if not db_config:
        return False

    conn = None
    cursor = None
    try:
        # print("更新: 建立新连接...") # Debug
        conn = pymysql.connect(**db_config)
        # print("更新: 连接成功。创建游标...") # Debug
        cursor = conn.cursor()
        # print(f"更新: 执行 {query[:60]}... 参数: {params}") # Debug
        cursor.execute(query, params)
        # print("更新: 提交事务...") # Debug
        conn.commit()
        rowcount = cursor.rowcount
        # print(f"更新: 提交成功。影响行数: {rowcount}") # Debug
        return True # 返回 True 表示成功
    except pymysql.Error as err:
        print(f"数据库操作失败 (PyMySQL): {err} (操作: {query[:60]}...) ({params})")
        if conn:
            try:
                # print("更新: 发生错误，回滚事务...") # Debug
                conn.rollback()
            except pymysql.Error as roll_err:
                 print(f"回滚事务时出错 (PyMySQL): {roll_err}")
        return False
    except Exception as e:
        print(f"执行数据库操作时发生未知错误 (PyMySQL): {e}")
        if conn:
             try:
                 conn.rollback()
             except Exception as roll_ex:
                  print(f"未知错误后回滚事务时出错 (PyMySQL): {roll_ex}")
        return False
    finally:
        if cursor:
            # print("更新: 关闭游标...") # Debug
            cursor.close()
        if conn:
            # print("更新: 关闭连接...") # Debug
            conn.close()

# --- 移除 if __name__ == '__main__' 块 --- 